const dbPcyData = require('./model_data');
const TAB_NAME = 'big_policy';

// big_policy表用来记录策略配置信息
// 对上关联uid和prod_id
// 对下关联dat_xxx策略数据表(借助policy_id表的外键)
module.exports = class Policy extends require('./model_pool')
{
  // 根据id查找策略
  static findById(uid, policyId)
  {
    return new Promise((resolve, reject)=>{
      let sql = 'SELECT * FROM '+TAB_NAME+' WHERE id=? AND uid=? AND del=0';
      this.query(sql,[policyId, uid]).then(results=>{
          resolve(results[0]);
      }).catch(err => {
          console.log('findById query faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 根据uid查找产品下所有策略
  static listByUid(uid, fields='*')
  {
    return new Promise((resolve, reject)=>{
      let sql = 'SELECT '+fields+' FROM '+TAB_NAME+' WHERE uid=? AND del=0';
      this.query(sql, [uid]).then(results=>{
          resolve(results);
      }).catch(err => {
          console.log('listByUid query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 根据prod id查找产品下所有策略
  static listByProdId(uid, prodId, fileds='*')
  {
    return new Promise((resolve, reject)=>{
      let sql = 'SELECT '+fileds+' FROM '+TAB_NAME+' WHERE prod_id=? AND uid=? AND del=0';
      this.query(sql,[prodId, uid]).then(results=>{
          resolve(results);
      }).catch(err => {
          console.log('listByProdId query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 新增一条策略
  static addItem(uid, data)
  {
    return new Promise((resolve,reject) => { //table为sql关键字 不能做字段名 需加`符号
      let sql = 'INSERT INTO `'+TAB_NAME+'` (uid,prod_id,type,class,name,master,brother,record_limit,options,db,debug,`table`)'
        +' VALUES(?,?,?,?,?,?,?,?,?,?,?,?)';
      this.query(sql, [uid, data.prod_id, data.type, data.class, data.name, data.master,
        data.brother, data.record_limit, data.options, data.db, data.debug, data.table]).then((res)=>{
        console.log(' + Add new policy [%d]', res.insertId);
        dbPcyData.recordPcyId(uid, res.insertId, data.prod_id).then(id=>{ // 记录id关系
          console.log('Patch new foreign key: policyId[%d] -> uid[%d] prod_id[%d]', res.insertId, uid, data.prod_id);
        }) // end recordPcyId
        resolve(res.insertId);
      }).catch(err=>{
        console.log('[%d]['+TAB_NAME+'] addItem faild:'+err.message, uid);
        reject(err);
      })
    })
  }

  // 删除一条策略，连带删除策略数据
  static deleteItem(uid, policy_id)
  {
    return new Promise((resolve,reject)=>{
      let sql='DELETE FROM `'+TAB_NAME+'` WHERE uid=? AND id=?';
      this.query(sql,[uid, policy_id]).then(results=>{
          dbPcyData.deletePcyId(uid, policy_id); // 删除id关系及所有dat外键数据
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('deleteItem query faild: '+err.message)
          reject(err);
      })
    })
  }

  // 修改属性，fields是对象
  static updateItem(uid, policy_id, fields, prod_id=null)
  {
    return new Promise((resolve,reject)=>{
      let kvArray = [];
      for (let key in fields) {
        let value = fields[key];
        kvArray.push('`'+key+'`='+`\'${value}\'`);
      }
      let sql = 'UPDATE `'+TAB_NAME+'` SET '+kvArray.join(',')+' WHERE uid=? AND id=? AND del=0';
      this.query(sql, [uid, policy_id]).then(results=>{
          if (prod_id) {
            dbPcyData.recordPcyId(uid, policy_id, prod_id).then(id=>{ // 补充记录id关系
              console.log('Patch new foreign key: policyId[%d] -> uid[%d] prod_id[%d]', policy_id, uid, prod_id);
            }) // end recordPcyId
          }
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('updateItem query faild: '+err.message)
          reject(err);
      })
    })
  }

  // 根据id得到产品下的策略数
  static getProdPolicyCount(uid, prod_ids)
  {
    return new Promise((resolve,reject) => {
      let idStr = Array.isArray(prod_ids) ? prod_ids.join(',') : prod_ids;
      let sql = 'SELECT prod_id,COUNT(id) AS policy_num FROM `'+TAB_NAME+
        '` WHERE uid=? AND del=0 AND prod_id IN('+idStr+') GROUP BY prod_id';
      this.query(sql, [uid]).then((res)=>{
        resolve(res);
      }).catch(err=>{
        console.log('[%d]['+TAB_NAME+'] getProdPolicyCount faild:'+err.message, uid);
        reject(err);
      })
    })
  }

  // 查找num个策略
  static fetch(num, debug=0)
  {
    return new Promise((resolve,reject)=>{
      let sql='SELECT * FROM `'+TAB_NAME+'` WHERE init=0 AND del=0 AND debug=? ORDER BY id LIMIT ?,?';
      this.query(sql,[debug, 0, num]).then(results=>{
          resolve(results);
      }).catch(err=>{
          console.log('fetch query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 查找num个被编辑的策略
  static fetchEdited(num, debug=0)
  {
    return new Promise((resolve,reject)=>{
      let sql='SELECT * FROM `'+TAB_NAME+'` WHERE init=2 AND del=0 AND debug=? ORDER BY id LIMIT ?,?';
      this.query(sql,[debug, 0, num]).then(results=>{
          resolve(results);
      }).catch(err=>{
          console.log('fetchEdited query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 查找num个被删除策略
  static fetchDel(num, debug=0)
  {
    return new Promise((resolve,reject)=>{
      let sql = 'SELECT * FROM `'+TAB_NAME+'` WHERE del=1 AND debug=? ORDER BY id LIMIT ?,?';
      this.query(sql, [debug, 0, num]).then(results=>{
          resolve(results);
      }).catch(err=>{
          console.log('fetchDel query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 设置所有记录的init为0
  // [0]待初始化 [1]初始化完毕 [2]编辑后待初始化
  static deInitAll(debug = 0)
  {
    return new Promise((resolve, reject)=>{
      let sql='UPDATE `'+TAB_NAME+'` set init=0 WHERE del=0 AND debug=?';
      this.query(sql,[debug]).then(results=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('deInitAll query faild: '+err.message)
          reject(err);
      })
    })
  }

  // 设置对应id之前的所有记录的init从2改为0，即从编辑态改为初始态
  static deInitEditedById(id1,id2,debug=0)
  {
    return new Promise((resolve,reject)=>{
      let sql='UPDATE `'+TAB_NAME+'` set init=0 WHERE id>=? AND id<=? AND init=2 AND del=0 AND debug=?';
      this.query(sql,[id1,id2,debug]).then(results=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('initById query faild: '+err.message)
          reject(err);
      })
    })
  }

  // 设置对应id之前的所有记录的init为1
  static initById(id1,id2,debug=0)
  {
    return new Promise((resolve,reject)=>{
      let sql='UPDATE `'+TAB_NAME+'` set init=1 WHERE id>=? AND id<=? AND del=0 AND debug=?';
      this.query(sql,[id1,id2,debug]).then(results=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('initById query faild: '+err.message)
          reject(err);
      })
    })
  }

  // 删除对应id之前的所有记录
  static deleteByIdSection(id1,id2,debug=0)
  {
    return new Promise((resolve,reject)=>{
      let sql='DELETE FROM `'+TAB_NAME+'` WHERE id>=? AND id<=? AND debug=?';
      this.query(sql,[id1,id2,debug]).then(results=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('deleteByIdSection query faild: '+err.message)
          reject(err);
      })
    })
  }



}